﻿using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Pay.Service {
    public class PayInfoService : ServiceBase, IPayInfoService, IDisposable {
        private IUnitOfWork _iUnitOfWork;

        public PayInfoService(IUnitOfWork iUnitOfWork) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
        }

        public pay_info_dto GetPayByPayNo(string PayNO) {
            return context.PayInfos.Where(x => x.PayNo == PayNO).FromCacheFirstOrDefault<PayInfo, pay_info_dto>();
        }
        /// <summary>
        /// 获取支付列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
		public List<pay_info_dto> Get(PayInfoQuery query) {
            var filter = PredicateBuilder.True<Data.PayInfo>();
            List<pay_info_dto> pay_infos = new List<pay_info_dto>();
            filter = filter.And(c => (c.BoardId == null || c.BoardId == 0) && c.PayChannel == PayChannel.SxyPay);
            //    filter = filter.And(c => c.TransactionNo != "");
            if (query.merchant_id > 0) {
                var pay_ids = context.Orders.Where(c => c.MerchantId == query.merchant_id).Select(c => c.PayId).ToList().ToArray();
                if (pay_ids.Length > 0)
                    filter = filter.And(c => pay_ids.Contains(c.Id));
            }
            if (query.boardid == 0)
                pay_infos = context.PayInfos.Where(filter).FromCache<Data.PayInfo, pay_info_dto>();
            if (query.boardid > 0)
                pay_infos = context.PayInfos.Where(c => (c.BoardId == query.boardid && c.PlateId == null) && c.PayChannel == PayChannel.SxyPay).FromCache<Data.PayInfo, pay_info_dto>();
            return pay_infos;
        }
        public pay_info_dto GetPayById(long Id) {
            return context.PayInfos.Where(x => x.Id == Id).FromCacheFirstOrDefault<PayInfo, pay_info_dto>();
        }
        public int Update(long Id, long LogistListId, int Type) {
            var model = context.PayInfos.Where(x => x.Id == Id).FirstOrDefault();
            if (Type == 1) {
                model.PlateId = LogistListId;
            } else {
                model.BoardId = LogistListId;
            }
            context.SaveChanges();
            return this._iUnitOfWork.Commit();
        }
        public List<pay_info_dto> GetListByPlateId(long Id) {
            return context.PayInfos.Where(x => x.PlateId == Id).FromCache<PayInfo, pay_info_dto>();
        }

        public List<pay_info_dto> GetListByBoardId(long Id) {
            return context.PayInfos.Where(x => x.BoardId == Id).FromCache<PayInfo, pay_info_dto>();
        }
    }
}